import { useRouter } from "vue-router"
import { ref, getCurrentInstance } from "vue"
import { ElMessage } from "element-plus"
export const useUser = () => {
  const { $http } = getCurrentInstance().appContext.config.globalProperties
  const router = useRouter()
  function logout() {
    localStorage.removeItem("token")
    localStorage.removeItem("userinfo")
    router.push("/login")
  }
  //用户管理
  const userDialog = ref(false)
  const users = ref([])
  function getAllUser() {
    users.value = []
    $http.get("/api/users").then(res => {
      res.data.forEach(item => {
        const { id, username, usertype } = item
        let usertype1 = ""
        switch (usertype) {
          case 0:
            usertype1 = "管理员"
            break
          case 1:
            usertype1 = "交通部门"
            break
          case 2:
            usertype1 = "普通用户"
            break
        }
        const obj = {
          id,
          username,
          usertype: usertype1,
        }
        users.value.push(obj)
      })
    })
  }
  function manageUser() {
    userDialog.value = true

    getAllUser()
  }
  function delUser(row) {
    $http.delete(`/api/users/${row.id}`).then(() => {
      getAllUser()
      ElMessage({
        message: "删除用户成功",
        type: "success",
      })
    })
  }
  const updateUserDialog = ref(false)
  const userForm = ref([])
  function editUser(row) {
    updateUserDialog.value = true
    userForm.value = row
  }
  function changeUserAuth() {
    $http.put("/api/users", userForm.value).then(res => {
      ElMessage({
        message: "修改用户权限成功",
        type: "success",
      })
      updateUserDialog.value = false
      getAllUser()
    })
  }
  async function delMyUser() {
    const { username } = JSON.parse(localStorage.getItem("userinfo"))
    const data = await $http.delete("/api/users/username", { data: { username } })
    if (data.code == 0) {
      localStorage.removeItem("userinfo")
      localStorage.removeItem("token")
      router.push("/login")
    }
  }
  return { logout, userDialog, users, updateUserDialog, userForm, editUser, delUser, changeUserAuth, manageUser, delMyUser }
}
